package com.crc.luojian.web;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.ServletException;

/**
 * @program: luojian-springframework
 * @description:
 * @author: luojian58
 * @create: 2021-06-10 15:53
 */
public class TomcatServer {

    private Tomcat tomcat;

    private String[] args;

    public TomcatServer(String[] args){
        this.args = args;
    }

    public void start( int port) throws LifecycleException, ServletException {
        tomcat = new Tomcat();
        tomcat.setPort(port);
        tomcat.setHostname("localhost");
        Context context = new StandardContext();
        context.setPath("");
        context.addLifecycleListener(new Tomcat.FixContextListener());
        DisPatcherServlet disPatcherServlet = new DisPatcherServlet();
        Tomcat.addServlet(context,"dispatcherServlet",disPatcherServlet)
                .setAsyncSupported(true);
        context.addServletMappingDecoded("/", "dispatcherServlet");
        tomcat.getHost().addChild(context);
        tomcat.start();
        //设置守护线程防止tomcat中途退出
        Thread awaitThread = new Thread("tomcat_await_thread."){
            @Override
            public void run() {
                TomcatServer.this.tomcat.getServer().await();
            }
        };
        //设置为非守护线程
        awaitThread.setDaemon(false);
        awaitThread.start();

    }
}
